#include <head.h>

int main(int argc, char const *argv[])
{
    int fd = open("test.txt", O_RDWR | O_CREAT, 0666);

    struct flock my_lock;
    my_lock.l_type = F_WRLCK;
    my_lock.l_whence = SEEK_SET;
    my_lock.l_len = 0;
    my_lock.l_start = 0;
    fcntl(fd, F_SETLKW, &my_lock); // 上锁

    int fd_T = open("T.txt", O_RDWR | O_CREAT, 0666);
    char buf[24] = "A";
    int i = 10;
    int T_num = 0;

    read(fd_T, &T_num, sizeof(int));
    lseek(fd, T_num, SEEK_SET);
    while (i--)
    {
        sleep(1);
        write(fd, buf, 1);
    }
    T_num = lseek(fd, 0, SEEK_CUR);
    lseek(fd_T, 0, SEEK_SET);
    write(fd_T, &T_num, sizeof(int));

    // 解锁
    my_lock.l_type = F_UNLCK; // 写锁
    fcntl(fd, F_SETLKW, &my_lock);
    close(fd);
    close(fd_T);
    return 0;
}
